<?php
namespace app\controller\admin\module\room;

use app\controller\admin\module\AdminBaseController;
use think\response\Json;
use think\response\View;

/**
 * @auth-name 房间列表
 * @auth-alias room
 */
class Index extends AdminBaseController
{
    protected string $modelName = 'room';
    /**
     * 主页
     * @auth-name 主页
     * @auth-alias index
     * @return View
     */
    public function index(): View
    {
        return fetch('/admin/room/index');
    }

    /**
     * @auth-name 列表
     * @auth-alias list
     * @return Json
     */
    public function list(): Json
    {
        $limit = values('limit', 10);
        $condition = [];
        $this->condition($condition);
        $list = $this->model->getPageList($condition, 'id, uid, opposite_uid, room_id, generation_method, addtime, state, state_code, close_time', 'addtime desc', ['start' => ((values('page', 10) - 1) * $limit), 'limit' => $limit]);
        $userInfos = getUserList((!empty($list['rows']) ? array_filter(array_unique(array_merge(array_column($list['rows'], 'uid'), array_column($list['rows'], 'opposite_uid')))) : []));
        if(!empty($userInfos)){
            $userInfos = array_column($userInfos, null, 'id');
            foreach($list['rows'] as $k => $v){
                $list['rows'][$k]['username'] = !empty($v['uid']) ? $v['uid'] . '-' . ($userInfos[$v['uid']]['username'] ?? '-') : '-';
                $list['rows'][$k]['opposite_username'] = !empty($v['opposite_uid']) ? $v['opposite_uid'] . '-' . ($userInfos[$v['opposite_uid']]['username'] ?? '-') : '-';
            }
        }
        return json($list);
    }

    private function condition(&$condition = []){
        $uidKeywordField = values('uid_keyword_field');
        $uidKeywordValue = values('uid_keyword_value');
        (!empty($uidKeywordField) and !empty($uidKeywordValue)) and $condition[$uidKeywordField] = $uidKeywordValue;
        //房间编号
        $room_id = values('room_id');
        $state = values('state');
        !empty($room_id) and $condition['room_id'] = $room_id;
        !empty($state) and $condition['state'] = $state;
    }

    /**
     * 关闭房间
     * @auth-name 关闭房间
     * @auth-alias close
     * @auth-request-method post
     * @return Json
     */
    public function close(): Json
    {
        $id = values('id');
        empty($id) and errorData();
        $roomInfo = $this->model->getInfo(['id' => $id], 'id, uid, opposite_uid, room_id, state');
        empty($roomInfo) and errorData();
        if($roomInfo['state'] != 1){
            return responseMsg('该房间已关闭');
        }
        $res = $this->model->edit(['id' => $id], ['state' => 2, 'close_time' => time(), 'state_code' => 1006]);
        if(!$res){
            return responseMsg('操作失败');
        }
        return responseMsg('关闭成功', 200);
    }

    /**
     * 详情
     * @auth-name 详情
     * @auth-alias details
     * @return View
     */
    public function details(): View
    {
        $id = values('id');
        empty($id) and errorData();
        $roomInfo = $this->model->getInfo(['id' => $id], 'id, room_id');
        empty($roomInfo) and errorData();
        return fetch('/admin/room/details', ['roomInfo' => $roomInfo]);
    }

    /**
     * 详情列表
     * @auth-name 详情列表
     * @auth-alias dlist
     * @return Json
     */
    public function detailsList(): Json
    {
        $id = values('id');
        empty($id) and errorData();
        $condition = [
            'rid' => $id
        ];
        $this->detailsListCondition($condition);
        $limit = values('limit', 10);
        $list = Model('roomPlayerInfo')->getPageList($condition, 'id, rid, match_id, white_uid, black_uid, starttime, endtime, outcome', 'id desc', ['start' => ((values('page', 10) - 1) * $limit), 'limit' => $limit]);
        $userInfos = getUserList((!empty($list['rows']) ? array_filter(array_unique(array_merge(array_column($list['rows'], 'white_uid'), array_column($list['rows'], 'black_uid')))) : []));
        if(!empty($userInfos)){
            $userInfos = array_column($userInfos, null, 'id');
            foreach($list['rows'] as $k => $v){
                $list['rows'][$k]['white_username'] = !empty($v['white_uid']) ? $v['white_uid'] . '-' . ($userInfos[$v['white_uid']]['username'] ?? '-') : '-';
                $list['rows'][$k]['black_username'] = !empty($v['black_uid']) ? $v['black_uid'] . '-' . ($userInfos[$v['black_uid']]['username'] ?? '-') : '-';
            }
        }
        return json($list);
    }


    private function detailsListCondition(&$condition = []){
        $uidKeywordField = values('uid_keyword_field');
        $uidKeywordValue = values('uid_keyword_value');
        (!empty($uidKeywordField) and !empty($uidKeywordValue)) and $condition[$uidKeywordField] = $uidKeywordValue;
//        $whiteUID = values('white_uid');
//        $blackUID = values('black_uid');
        $startTime = values('start_time');
        $endTime = values('end_time');
        $result = values('outcome');
//        !empty($whiteUID) and $condition['white_uid'] = $whiteUID;
//        !empty($blackUID) and $condition['black_uid'] = $blackUID;
        !empty($startTime) and $condition['starttime'] = ['>=', strtotime($startTime)];
        !empty($endTime) and $condition['endtime'] = ['<=', strtotime($endTime)];
        !empty($result) and $condition['outcome'] = $result;
    }

    /**
     * 结束棋局
     * @auth-name 结束棋局
     * @auth-alias end
     * @auth-request-method post
     * @return Json
     */
    public function endMatch(): Json
    {
        $id = values('id');
        empty($id) and errorData();
        $model = Model('roomPlayerInfo');
        $roomPlayerInfo = $model->getInfo(['id' => $id], 'id, rid, outcome');
        empty($roomPlayerInfo) and errorData();
        $roomInfo = $this->model->getInfo(['id' => $roomPlayerInfo['rid']], 'id, room_id, state');
        empty($roomInfo) and errorData();
        if($roomInfo['state'] != 1){
            return responseMsg('房间已经关闭了');
        }
        if($roomPlayerInfo['outcome'] != 0){
            return responseMsg('棋局已经结束');
        }
        $result = $model->edit(['id' => $id], ['outcome' => 1006, 'endtime' => time()]);
        if($result){
            return responseMsg('棋局结束', 200);
        }else{
            return responseMsg('棋局结束失败');
        }
    }
}